/** @jsxImportSource @emotion/react */
import * as React from "react";
import {css} from "@emotion/react";
import {
  CCell, Table, TableBody, TableRow, Text, TableHead, BlobInputList, Button, TextArea, Cell,
} from "customize-easy-ui-component";
import {InspectRecordLayout, InternalItemProps, RepLink, useItemInputControl} from "../../common/base";
import {useOmnipotentPrefCs, useOmnipotentPrefTitle} from "../../hook/useOmnipotentPref";
import {TailMenRowIspCheck} from "../../contain/rarelyVary";
import {useMeasureInpFilter} from "../../common/hooks";
import {objNestSet,} from "../../../common/tool";
import {MemoDateInput} from "../../../comp/base";
import {useContext} from "react";
import UserContext from "../../../routing/UserContext";


interface Props extends InternalItemProps {
  iAname?: string[];
  part?: number;
}
//新的配置模式：多了 cs参数;
const item检验项 = [
  ['改造许可', [{t:'资源条件', s: 4,cs:1}, {cs:-1}], '修理、改造许可证', 'A'],
  ['改造告知', [{}, {cs:-1}], '修理、改造告知书',  'A'],
  ['人员配置', [{}, {cs:-1}], '相关责任人员配置，焊接人员、无损检测人员的持证情况', 'C' ],
  ['其他资源', [{}, {cs:-1}], '合格委托方、供方及锅炉修理、改造的其他资源条件', 'C' ],
  ['改造设计', [{t:'施工工艺文件', s: 4}, ], '改造设计文件', 'A'],
  ['组织方案', [{}], '修理改造施工组织方案', 'A'],
  ['工艺评定', [{}], '焊接工艺评定的引用', 'C'],
  ['工艺文件', [{}], '焊接工艺及其他工艺文件', 'C'],
    //1+2col布局的
  ['出厂资料', [{t:'材料', s: 3,cs:1}, {cs:-1}], '涉及修理改造的锅炉部件出厂资料和制造监督检验证书', 'A'],
  ['购件质量', [{},{cs:-1}], '钢板、管子、管件、法兰、阀门、紧固件等外购件质量', 'A'],
  ['焊材质量', [{},{cs:-1}], '焊接材料质量证明文件', 'C'],
  ['焊接质量', [{t:'现场施工质量检查', s: 7,cs:1},{t:'焊接质量',s: 2}], '焊接工艺执行情况', 'B'],
  ['接头外观', [{},  ], '焊接接头外观质量', 'B'],
  ['过程质量', [{},{cs:-1}], '施工过程相关质量记录', 'C'],
  ['质量抽查', [{},{cs:-1}], '现场施工质量抽查（如受热面更换）', 'B'],
  ['无损检报', [{},{t:'无损检测',s: 2}], '无损检测报告', 'C'],
  ['射线片', [{},  ], '射线底片', 'C'],
  ['接头硬', [{},{cs:-1}], '高合金钢材料焊接接头的硬度（受热面管除外）,必要时进行无损检测检查', 'B'],
    //2col+1布局的
  ['压试准备', [{t:'耐压试验', s: 2}, ], '试验前准备工作', 'A'],
  ['压试监督', [{}], '试验过程及结果现场监督',  'A'],
  ['燃器合证', [{t:'液(气）体燃料燃烧器的更换、修理、改造', s: 3}, ], '型式试验合格证书', 'A'],
  ['燃器宏检', [{}], '完工后宏观检查',  'B'],
  ['燃器调试', [{}], '调试结果',  'C'],
  ['竣工资料', [], '竣工资料',  'C'],
  ['改造单体', [], '修理改造单位的质量管理体系运转情况检查',  'B'],
  ['能效测', [], '锅炉及其系统能效测试',  'C'],
  ['污染排放', [], '锅炉改造后，应提供符合相关法规、技术规范要求的锅炉大气污染物排放测试报告',  'C'],
];

const 工作见证选=['资料确认','资料确认实物检查','资料确认、实物检查、现场监督','过程巡检','现场确认','核查报告'];
export const itemA检验项: string[] = ['记事' ];
item检验项.forEach(([name, title, initIsp], i: number) => {
    itemA检验项.push(name as string);
});
//【项目表拆分有讲究】大数组拆几个小数组，没办法继承前缀部分的配置；所以要求不要从前缀标题的中间拆开，除非span也一起拆分配置加上{t:?,s:?}才行，否则编辑器没有完整的前缀描述区域信息。
const item检验项1=item检验项.slice(0,11);
const item检验项2=item检验项.slice(11,item检验项.length);
export const InspectionItem =
    React.forwardRef((
        {children, show, alone = true, refWidth, label, part}: Props, ref
    ) => {
      const {user} = useContext(UserContext);
      const {inp, setInp} = useItemInputControl({ref});
      // const itemA = React.useMemo(() => {
      //   return [ ...iAname ?? [], ...itemA检验项 ];
      // }, [ iAname ]);
      const [getInpFilter] = useMeasureInpFilter(null, itemA检验项,);
      const baseSeq= part===1? 0: item检验项1.length;
      const config = part===1? item检验项1: item检验项2;
      const titNode=useOmnipotentPrefTitle({config, baseSeq});
      return (
          <InspectRecordLayout inp={inp} setInp={setInp} getInpFilter={getInpFilter} show={show}
                               alone={alone} label={label!}>
            <Text variant="h5">{label}：</Text>
            {config.map(([name, _1, _2, unit]: any, i: number) => {
              return (<React.Fragment key={i}>
                <div css={{display: 'flex', flexWrap: 'wrap', alignItems: 'center'}}>
                  {titNode[i]}
                  &nbsp; 类别：{unit} &nbsp;
                  <div css={{display: 'inline-flex', alignItems: 'center', flexWrap: 'wrap'}}>
                    检查结果：
                    <BlobInputList value={inp?.[name]?.r || ''} datalist={['√', '○', '—', '×']} rows={1}
                                   style={{
                                     display: 'inline-flex',
                                     width: '6rem',
                                     maxWidth: '100%',
                                     fontSize: '1.1rem',
                                   }}
                                   listStyle={css({fontSize: '1.4rem',})}
                                   onListChange={v => objNestSet(name, 'r', v || undefined, inp, setInp)}/>
                  </div>
                  <div css={{display: 'inline-flex', alignItems: 'center', flexWrap: 'wrap'}}>
                    工作见证：
                    <BlobInputList value={inp?.[name]?.z || ''} datalist={工作见证选} rows={1}
                                   style={{
                                     display: 'inline-flex',
                                     width: '16rem',
                                     maxWidth: '100%',
                                   }}
                                   onListChange={v => objNestSet(name, 'z', v || undefined, inp, setInp)}/>
                  </div>
                  <div css={{display: 'inline-flex', alignItems: 'center', flexWrap: 'wrap'}}>
                    确认日期
                    <MemoDateInput value={inp?.[name]?.d || ''}
                                   onChange={v => objNestSet(name,'d', v||undefined,inp,setInp) } />
                  </div>
                  签字人：{inp?.[name]?.sgm?.name || ''}。<br/>
                  {inp?.[name]?.sgm?.username === user?.username ?
                      <Button intent="warning"
                              onPress={async () => {
                                    // await tableSetInp('单图表', dxtix, inp, setInp, 'sgm', undefined);
                                await objNestSet(name,'sgm', undefined, inp,setInp);
                              }}
                      >去除签名</Button>
                      :
                      <Button intent="warning"
                              onPress={async () => {
                                const me = {username: user?.username, name: user?.person?.name};
                                    // await tableSetInp('单图表', dxtix, inp, setInp, 'sgm', me);
                                await objNestSet(name,'sgm', me, inp,setInp);
                              }}
                      >签名</Button>
                  }
                </div>
              </React.Fragment>);
            })}
            <hr/>
            记事:
            <TextArea  value={inp?.记事 ||''} rows={6}
                       onChange={e => setInp({ ...inp, 记事: e.currentTarget.value||undefined}) } />
            <Text>
              注：结果栏中符合要求打“√”，基本符合要求打“○”，不符合要求打“×”，没有的项目打“—”，已整改打“△”。
            </Text>
            {children}
          </InspectRecordLayout>
      );
  });

const tailRender = (orc: any, name: string, lix: number, unit: any) => {
  const nneedbig = orc?.[name]?.r?.length >= 3 || (!orc?.[name]?.r);
  return <>
    <CCell><Text css={{fontSize: nneedbig ? '0.875rem' : '1.15rem'}}>{orc?.[name]?.r ?? '／'}</Text></CCell>
    <CCell>{orc?.[name]?.z ?? '／'}</CCell>
    <CCell>{orc?.[name]?.sgm?.name ?? '／'}</CCell>
    <CCell>{orc?.[name]?.d ?? '／'}</CCell>
  </>;
}

//有点类似： 机电类报告的项目列表；
export const InspectionItemVw = ({orc, rep}: { orc: any, rep: any }
) => {
  const [renderP1,renderP2] = useOmnipotentPrefCs({orc, config: item检验项, split:[10], tag:'XmbIspItms',
                  tailRender, pcols: 2, noNo: false, unitCel: true});
  return <>
    <div css={{"@media print": {paddingBottom: '3.5rem', pageBreakInside: 'avoid'}}}>
      <Text id='InspectionItem' variant="h2" css={{
        textAlign: 'center', marginTop: '1rem',
      }}>工业锅炉修理、改造监督检验项目</Text>
      <div css={{display: 'flex', justifyContent: 'space-between'}}>
        <Text></Text>
        <Text>报告编号：{rep.isp.no}</Text>
      </div>
    </div>
    <Table fixed={ ["4%", "8%", "5%","%", "3.3%", "6%","22%","6.6%","11%"] }
           css={{borderCollapse: 'collapse', "@media print": {marginTop: '-3.5rem'}}} tight miniw={800}>
      <TableHead>
        <TableRow>
          <CCell><Text css={{fontSize: '0.75rem'}}>序号</Text></CCell><CCell
            colSpan={3}>监检项目、内容</CCell><CCell>类别</CCell>
          <CCell>检查结果</CCell><CCell>工作见证</CCell><CCell>监检员</CCell><CCell>确认日期</CCell>
        </TableRow>
      </TableHead>
      <TableBody>
        <RepLink rep={rep} tag={'InspectionItem'}>
          {renderP1}
        </RepLink>
        <RepLink rep={rep} tag={'XmbIspItms_12'}>
          {renderP2}
          <TableRow>
            <Cell split={true} colSpan={9}>
              <div css={{minHeight: '2rem', whiteSpace: 'pre-wrap'}}>
                记事：<br/>{orc?.记事 || '／'}
              </div>
            </Cell>
          </TableRow>
        </RepLink>
      </TableBody>
    </Table>
    <TailMenRowIspCheck cap={'监检'} orc={orc} rep={rep} href={`/report/${rep?.modeltype}/ver/${rep?.modelversion}/${rep?.id}/Conclusion#Conclusion`}>
    </TailMenRowIspCheck>
    <Text css={{fontSize:'0.75rem'}}>
      填写说明：检查结果栏可用“√”表示符合，“○”表示基本符合，“×”表示不符合，“－”或“/”表示无此项。
    </Text>
  </>;
};
